<?php

/*
 * Copyright 20068 Jeffrey Palm
 */

define('FILL_THIS_IN', 'FILL THIS IN');

/**
 * @param $outdir the output directory for images
 * @param $sec    the value from datetime(), needed later.
 */
function fullImageFileName($outdir,$sec) {
  return $outdir . $sec . "-full.jpg";
}

/**
 * Taken from <a href="http://www.4wordsystems.com/php_image_resize.php">
 * http://www.4wordsystems.com/php_image_resize.php</a>.
 *
 * @param $file input file
 * @param $outFile output file
 * @param $newWidth new width
 * @param $newHeight new height
 */
function resizeImage($infile,$outFile,$newWidth,$newHeight) {
  $src = imagecreatefromjpeg($infile);
  list($width,$height) = getimagesize($infile);
  $ratio_orig = $width/$height;
  
  if ($newWidth/$newHeight > $ratio_orig) {
    $newWidth = $newHeight*$ratio_orig;
  } else {
    $newHeight = $newWidth/$ratio_orig;
  }
  $tmp = imagecreatetruecolor($newWidth,$newHeight);
  imagecopyresampled($tmp,$src,0,0,0,0,$newWidth,$newHeight,$width,$height);
  imagejpeg($tmp,$outFile,100);
  imagedestroy($src);
  imagedestroy($tmp);
  }

function randomWord($N=40) {
  $chars = "abcdefghijkmnopqrstuvwxyz023456789";
  srand((double)microtime()*1000000);
  $res = '';
  for ($i=0; $i<$N; $i++) {
    $res .= substr($chars, rand() % 33, 1);
  }
  return $res;
}

function readNames($base) {
  $names = array();
  if (! $dh = opendir($base) ) {
    die("Whoops, couldn't open $base!");
  }
  if (!preg_match('/\/$/',$base)) {
    $base .= '/';
  }
  while (($fileName = readdir($dh)) !== false) {
    if (preg_match("/\d+.jpg$/i",$fileName) && !is_dir($base . "/" . $fileName)) {
      $name = $fileName;
      $name = preg_replace('/\..*/','',$name);
      $name = preg_replace('/\.jpg$/','',$name);

      // maybe add it
      $des = $base . $name . '.des';
      $loc = $base . $name . '.loc';
      if (!is_file($des)) continue;
      if (!is_file($loc)) continue;
      $names[] = $name;
    }
  }
  rsort($names);
  return $names;
}

function warn($msg) {
  say($msg,"#770000");
}

function note($msg) {
  say($msg,"#007700");
}

function say($msg,$color) {
  echo '<font color="' . $color . '">' . $msg . '</font><br/>';
  }

function option($name) {
  global $CONFIG;
  global $EXAMPLE;
  $value = $CONFIG[$name];
  if ((!$value || $value == FILL_THIS_IN) && $EXAMPLE[$name]) {
    $value = $EXAMPLE[$name];
  }
  echo $name . '<br/><input type="text" value="' . htmlspecialchars($value) . '" name="' . $name . '" />';
}

function config($key,$required=TRUE) {
  global $CONFIG;
  $val = $CONFIG[$key];
  if (!$val) {
    $val = $_REQUEST[$key];
  }
  if ($required && !$val) {
    note("ERROR: Required value for '$key'");
  }
  return $val;
}

function connect($user,$pass) {
  if (isset($user) && $user && isset($pass) && $pass) {
    
    // if there is no '@' put the server name
    // after the user name, but don't keep any
    // leading www's
    if (!preg_match('/.*@.*/',$user)) {
      $server = $_SERVER['SERVER_NAME'];
      $server = preg_replace('/^www\./','',$server);
      $user = $user . '@' . $server;
    }
  }
  return imap_open("{localhost:143}INBOX", $user, $pass);
  }

function newline() {
  echo '<br/>';
}

/** i is a month 1 to 12 */
function number2month($i) {
  if ($i=="01") return "Jan";
  if ($i=="02") return "Feb";
  if ($i=="03") return "Mar";
  if ($i=="04") return "Apr";
  if ($i=="05") return "May";
  if ($i=="06") return "Jun";
  if ($i=="07") return "Jul";
  if ($i=="08") return "Aug";
  if ($i=="09") return "Sep";
  if ($i=="10") return "Oct";
  if ($i=="11") return "Nov";
  if ($i=="12") return "Dec";
}

function readFileAll($filename) {
  if (!file_exists($filename)) return "";
  $res = stripslashes(file_get_contents($filename));
  $res = preg_replace('/^\s+/','',$res);
  $res = preg_replace('/\s+$/','',$res);
  return $res;
}

function format_date($dt) {

  //20060226062615
  $year      = substr($dt, 0, 4);
  $month     = substr($dt, 4, 2);
  $day       = substr($dt, 6, 2);
  $hour      = substr($dt, 8, 2);
  $minutes   = substr($dt,10, 2);
  $seconds   = substr($dt,12, 2);

  $monthString = number2month($month);
  
  $d = $day;

  $h = $hour;
  if ($h == 0) $h = 12; # midnight
  $m = $minutes;
  $s = $seconds;

  $amPm;
  if ($h > 12) {
    $h -= 12;
    $amPm = "pm";
  } else {
    $amPm = "am";
  }

  return "$monthString $d, $year @ $h:$m $amPm";
}

function doExec($cmd) {
  say($cmd,'#000077');
  exec($cmd);
}

function writeFile($filename,$contents) {
  note("Writing to '$filename'");
  $handle = fopen($filename,"w");
  if (fwrite($handle, $contents) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
  }
  fclose($handle);
}

function datetime() {
  $DATE_FORMAT = "YmdHis";
  return date($DATE_FORMAT);
}

/**
 * Removes the email address from $line returned by
 * <code>imap_headerinfo->fromaddress</code>.
 *
 * @param line string returned from <code>imap_headerinfo->fromaddress</code>
 */
function getNameFromEmail($line) {
  if (preg_match('/([^<]+)\s*</',$line,$out)) {
    return removeWhitespace($out[1]);
  }
  if (preg_match('/([^@]+)@/',$line,$out)) {
    return removeWhitespace($out[1]);
  }
  return $line;
}

function removeWhitespace($s) {
  $s = preg_replace('/^\s+/','',$s);
  $s = preg_replace('/\s+$/','',$s);
  return $s;
}


/**
 * Returns dimension string given width and height, i.e. <code>$width
 * . 'x' . $height</code>.
 *
 * @ dimension string given width and height, i.e. <code>$width . 'x'
 * . $height</code>.
 */
function dimension($width,$height) {
  return $width . 'x' . $height;
}

/**
 * Shortcut for <code>dimension($width,$height).
 */
function x($width,$height) {
  return dimension($width,$height);
}

function getPhotoNames($theID,$base=".") {
  global $names;
  // Name of all the photos (\d+)
  if ($theID == -1 || !maybeAdd($base,$theID)) {
    // find all the photos that are just numbers
    if (! $dh = opendir($base) ) {
      die("Whoops, couldn't open $base!");
    }
    while (($fileName = readdir($dh)) !== false) {
      if (preg_match("/\d+.jpg$/i",$fileName) && !is_dir($base . "/" . $fileName)) {
        $name = preg_replace('/\..*/','',$fileName);
        maybeAdd($base,$name);
      }
    }
  }
  rsort($names);
}

function fullImageName($name) {
  return $name . '-full.jpg';
}

function getDescription($name) {
  return readFileAll($name . '.des');
}

function getLocation($name) {
  return readFileAll($name . '.loc');
}


?>